package factory.one.service;

import factory.one.entity.DeliverItem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.stereotype.Service;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

/**
 * @author sk.z
 * 2023/11/9
 **/
@Service
public class DeliverItemService {

    private final Logger log = LoggerFactory.getLogger(DeliverItemService.class);
    private final JdbcTemplate jdbcTemplate;

    public DeliverItemService(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public Long add(DeliverItem add) {
        PreparedStatementCreator creator = con -> {
            PreparedStatement statement = con.prepareStatement(
                    "insert into DELIVERITEM(deliver_id,batch_id,number) values(?,?,?)",
                    Statement.RETURN_GENERATED_KEYS);
            statement.setLong(1, add.getDeliverId());
            statement.setLong(2, add.getBatchId());
            statement.setInt(3, add.getNumber());
            return statement;
        };
        GeneratedKeyHolder holder = new GeneratedKeyHolder();
        jdbcTemplate.update(creator, holder);
        return holder.getKey() == null ? null : holder.getKey().longValue();
    }

    public List<DeliverItem> listByDeliver(Long deliverId) {
        return jdbcTemplate.query("select * from DELIVERITEM where deliver_id = ?", new DeliverItemRowMapper(), deliverId);
    }

    public int updateNumberById(Long id, Integer number) {
        return jdbcTemplate.update("update DELIVERITEM set NUMBER = ? where id = ?", number, id);
    }

    private static class DeliverItemRowMapper implements RowMapper<DeliverItem> {

        @Override
        public DeliverItem mapRow(ResultSet rs, int rowNum) throws SQLException {
            DeliverItem o = new DeliverItem();
            o.setId(rs.getLong("id"));
            o.setDeliverId(rs.getLong("deliver_id"));
            o.setBatchId(rs.getLong("batch_id"));
            o.setNumber(rs.getInt("number"));
            return o;
        }
    }

}
